
package com.jml.jm_usb

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConfiguration
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import android.hardware.usb.UsbRequest
import android.os.Build
import android.os.HandlerThread
import android.util.Log
import androidx.annotation.RequiresApi
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.LinkedList
import java.util.Queue
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Executors
import java.util.concurrent.locks.LockSupport
import kotlin.time.Duration.Companion.microseconds


// 建议的回调类型，传递数据、偏移量和长度，以避免不必要的数组拷贝
// 如果您确实需要每次回调都得到一个全新的、精确大小的 ByteArray，
// 可以在回调的实现侧进行拷贝，或者我们可以在此函数内部调整。
// 但为了最高性能，推荐此签名。
typealias DataCallback = (data: ByteArray?) -> Unit
typealias DataCallback2 = (data: ByteArray, length: Int) -> Unit
typealias DataLengthCallback = (length: Int) -> Unit

interface UsbStatusCallback {
    fun onComplete(b: Boolean)
    fun onComplete(b: Boolean, message: String, value: Int = 0){
        // 默认实现，子类可以选择覆盖
        Log.d("UsbStatusCallback", "onComplete: b = $b, message = $message, value = $value")
    }
}



object Usb {
    private const val tag = "JmUsb"

    private const val ACTION_USB_PERMISSION = "com.lemai.jiyibao_test.USB_PERMISSION"

    private val highPriorityDispatcher by lazy {
        // 创建单线程线程池，并把线程优先级设为比较高的等级
        java.util.concurrent.Executors.newSingleThreadExecutor { r ->
            Thread(r, "HighPriorityUsbThread").apply {
                // 在线程创建时，把该线程的优先级调高
                // 可以根据需要使用 -4 / -8 / -16 等不同等级
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO)

            }
        }.asCoroutineDispatcher()
    }



    private val pendingIntentFlag =
        if (Build.VERSION.SDK_INT >= 34) { // Android U+ (Version 34)
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // Android 12 (Version 31)
            PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        } else {
            PendingIntent.FLAG_UPDATE_CURRENT
        }

    private fun pendingPermissionIntent(context: Context): PendingIntent {
        // 创建带有 FLAG_IMMUTABLE 的 PendingIntent 来符合 Android U+ 的要求
        val intent = Intent(ACTION_USB_PERMISSION)
        return PendingIntent.getBroadcast(context, 0, intent, pendingIntentFlag)
    }

    private var applicationContext: Context? = null // 声明一个上下文对象
    private var usbManager: UsbManager? = null // 声明一个USB管理器对象
    private var usbDeviceList: HashMap<String, UsbDevice>? = null // 声明一个USB设备列表对象
    private var usbDevice: UsbDevice? = null // 声明一个USB设备对象
    private var usbDeviceConnection: UsbDeviceConnection? = null // 声明一个USB设备连接对象
    private var usbConfiguration: UsbConfiguration? = null // 声明一个USB设备配置对象
    private var usbInterface: UsbInterface? = null // 声明一个USB接口对象
    private var usbEndpointIn: UsbEndpoint? = null // 声明一个USB输入端点对象
    private var usbEndpointOut: UsbEndpoint? = null // 声明一个USB输出端点对象

    public var verifyDeviceSuccess = false
    private var dataListeningRunning = false
    private var dataLengthSum = 0 // 用于统计数据长度的总和

    private var dataListeningThread: Thread? = null
    // 用于读取线程和处理线程之间传递数据的队列
    private val dataQueue: Queue<ByteArray> = ConcurrentLinkedQueue()

    fun init(context: Context,callback: DataLengthCallback) {
        applicationContext = context.applicationContext // 获取应用的上下文
        usbManager =
            applicationContext?.getSystemService(Context.USB_SERVICE) as UsbManager // 获取USB管理器
        Log.d(tag, "init: usbManager = $usbManager")

        //建立一个1秒调用一次的定时器，上报当前收到的数据量
        val handlerThread = HandlerThread("UsbDeviceMonitor")
        handlerThread.start()
        val handler = android.os.Handler(handlerThread.looper)
        handler.postDelayed(object : Runnable {
            override fun run() {
                if(dataListeningRunning){
                    callback(dataLengthSum)
                    dataLengthSum = 0 // 重置数据长度总和
                }
                handler.postDelayed(this, 1000) // 每1秒检查一次
            }
        }, 1000)
    }

    fun usbDeviceForIdentifier(identifier: String): UsbDevice? {
        return usbDeviceList?.get(identifier)
    }

    fun getDeviceList(): HashMap<String, UsbDevice> {
        if (usbManager == null) {
            Log.e(tag, "getDeviceList: usbManager is null")
            return HashMap()
        }
        usbDeviceList = usbManager?.deviceList // 获取USB设备列表

        Log.d(tag, "getDeviceList: usbDeviceList = $usbDeviceList")
        return usbDeviceList!!
    }

    fun quickConnectDevice(device: UsbDevice,
                           configurationIndex: Int,
                            interfaceIndex: Int,
                            endpointInIndex: Int?,
                            endpointOutIndex: Int?,
                           callback: UsbStatusCallback, ) {

        Log.d(tag, "quickConnectDevice: device = ${device.deviceName}, configurationIndex = $configurationIndex, interfaceIndex = $interfaceIndex, endpointInIndex = $endpointInIndex, endpointOutIndex = $endpointOutIndex")
        requestPermission(device, object : UsbStatusCallback {
            override fun onComplete(b: Boolean) {
                if (b) {
                    val openRes = openDevice(device)
                    if (!openRes) {
                        Log.w(tag, "onComplete: 打开USB设备失败, 请重新插拔USB设备")
                        return callback.onComplete(false)
                    }

                    val getConfigurationRes =  getConfiguration(configurationIndex) // 获取USB设备配置
                    if (!getConfigurationRes) {
                        Log.w(tag, "onComplete: 获取USB设备配置失败")
                        return callback.onComplete(false)
                    }

                    val interfaceCount = usbConfiguration?.interfaceCount
                    if (interfaceCount == null || interfaceCount <= 0) {
                        Log.w(tag, "onComplete: interfaceCount = $interfaceCount")
                        return callback.onComplete(false)
                    }else{
                        Log.d(tag, "onComplete: interfaceCount = $interfaceCount")
                    }

                    if (interfaceIndex >= interfaceCount) {
                        Log.w(tag, "onComplete: interfaceIndex超出范围，interfaceIndex = $interfaceIndex，interfaceCount = $interfaceCount")
                        return callback.onComplete(false)
                    }

                    val getInterfaceRes = getInterface(interfaceIndex) // 获取USB接口
                    if (!getInterfaceRes) {
                        Log.w(tag, "onComplete: 获取USB接口失败")
                        return callback.onComplete(false)
                    }else{
                        Log.d(tag, "onComplete: 获取USB接口成功")
                    }

                    val claimInterfaceRes = claimInterface() // 获取USB接口权限
                    if (!claimInterfaceRes) {
                        Log.w(tag, "onComplete: 获取USB接口权限失败")
                        return callback.onComplete(false)
                    }else{
                        Log.d(tag, "onComplete: 获取USB接口权限成功")
                    }

                    val setInterfaceRes = setInterface() // 设置USB接口
                    if (!setInterfaceRes) {
                        Log.w(tag, "onComplete: 设置USB接口失败")
                        return callback.onComplete(false)
                    }else{
                        Log.d(tag, "onComplete: 设置USB接口成功")
                    }


                    val getEndpointRes = getEndpoint(endpointInIndex,endpointOutIndex) // 获取USB端点
                    if (!getEndpointRes) {
                        Log.w(tag, "onComplete: 获取USB端点失败")
                        return callback.onComplete(false)
                    }else{
                        Log.d(tag, "onComplete: 获取USB端点成功")
                    }
                    //controlTransferOut(161, 254, 0, 0, ByteArray(1))
                    Log.d(tag, "connectDevice: usbDeviceConnection = $usbDeviceConnection")

                    return callback.onComplete(true)

                } else {
                    Log.w(tag, "onComplete: 申请USB权限失败")
                    return callback.onComplete(false)
                }
            }
        })
    }

    fun quickGetFileDescriptor(device: UsbDevice,
                               configurationIndex: Int,
                               interfaceIndex: Int,
                               endpointInIndex: Int?,
                               endpointOutIndex: Int?,
                           callback: UsbStatusCallback, ) {

        Log.d(tag, "getFileDescriptor: device = ${device.deviceName}, configurationIndex = $configurationIndex, interfaceIndex = $interfaceIndex, endpointInIndex = $endpointInIndex, endpointOutIndex = $endpointOutIndex")
        requestPermission(device, object : UsbStatusCallback {
            override fun onComplete(b: Boolean) {
                if (b) {
                    val openRes = openDevice(device)
                    if (!openRes) {
                        Log.w(tag, "onComplete: 打开USB设备失败, 请重新插拔USB设备")
                        return callback.onComplete(false, "打开USB设备失败, 请重新插拔USB设备")
                    }

                    val fileDescriptor = getFileDescriptor() // 获取USB设备的文件描述符
                    if (fileDescriptor < 0) {
                        Log.w(tag, "onComplete: 获取USB设备文件描述符失败")
                        return callback.onComplete(false, "获取USB设备文件描述符失败")
                    } else {
                        Log.d(tag, "onComplete: 获取USB设备文件描述符成功, fileDescriptor = $fileDescriptor")
                    }




                    return callback.onComplete(true, "获取USB设备文件描述符成功", fileDescriptor)

                } else {
                    Log.w(tag, "onComplete: 申请USB权限失败")
                    return callback.onComplete(false, "申请USB权限失败")
                }
            }
        })
    }

    //获取连接设备的serialNumber
    fun getSerialNumber(): String {
        if (usbDevice == null) {
            Log.d(tag, "getSerialNumber: usbDevice is null")
            return ""
        }
        try {
            return usbDevice?.serialNumber ?: ""
        } catch (e: Exception) {
            Log.w(tag, "getSerialNumber: ${e.message}")
        }

        return ""
    }

    //getFileDescriptor
    /**
     * 获取USB设备的文件描述符
     * @return 文件描述符，失败返回 -1
     */

    fun getFileDescriptor(): Int {
        if (usbDeviceConnection == null) {
            Log.e(tag, "getFileDescriptor: usbDeviceConnection is null")
            return -1
        }
        val fileDescriptor = usbDeviceConnection?.fileDescriptor ?: return -1 // 获取USB设备的文件描述符
        Log.d(tag, "getFileDescriptor: fileDescriptor = $fileDescriptor")
        return fileDescriptor
    }

    fun hasPermission(device: UsbDevice): Boolean {
        if (usbManager == null) {
            Log.e(tag, "hasPermission: usbManager is null")
            return false
        }
        return usbManager?.hasPermission(device) ?: false // 判断是否有权限
    }

    fun requestPermission(device: UsbDevice, callback: UsbStatusCallback) {
        Log.d(tag, "requestPermission: device = ${device.deviceName}")
        if (usbManager == null) {
            Log.w(tag, "requestPermission: usbManager is null")
            return callback.onComplete(false)
        }
        if (usbManager?.hasPermission(device) == true) { // 判断是否有权限
            Log.d(tag, "requestPermission: 已经有USB权限")
            return callback.onComplete(true)
        }



        val receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                Log.d(tag, "申请USB权限回调 onReceive: intent = $intent")
                context.unregisterReceiver(this)
                //val usbDevice = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                //val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                val hasPermission = usbManager?.hasPermission(device) == true
                Log.d(tag, "申请USB权限 onReceive: usbDevice = ${device.deviceName}, hasPermission = $hasPermission")
                callback.onComplete(hasPermission)
            }


        }

        // Android 12 及以上的版本需要指定广播接收器的导出状态
        val intentFilter = IntentFilter(ACTION_USB_PERMISSION)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            applicationContext!!.registerReceiver(receiver, intentFilter, Context.RECEIVER_EXPORTED)
        } else {
            applicationContext!!.registerReceiver(receiver, intentFilter)
        }

        try {
            // 使用带有 FLAG_IMMUTABLE 的 PendingIntent 符合最新的系统要求
            val pendingIntent = pendingPermissionIntent(applicationContext!!)
            //val pendingIntent = PendingIntent.getBroadcast(applicationContext, 0, Intent(UsbManager.ACTION_USB_DEVICE_PERMISSION), PendingIntent.FLAG_IMMUTABLE)
            usbManager?.requestPermission(device, pendingIntent)
            Log.d(tag, "requestPermission: 申请USB权限2")
        } catch (e: Exception) {
            Log.e(tag, "requestPermission: ${e.message}")
            callback.onComplete(false)
        }


    }



    fun openDevice(device: UsbDevice): Boolean {
        if (usbManager == null) {
            Log.e(tag, "openDevice: usbManager is null")
            return false
        }
        usbDevice = device // 获取USB设备
        usbDeviceConnection = usbManager?.openDevice(usbDevice) // 打开USB设备
        Log.d(tag, "openDevice: usbDeviceConnection = $usbDeviceConnection")

        usbDeviceConnection?.fileDescriptor?.let {
            Log.d(tag, "openDevice: usbDeviceConnection fileDescriptor = $it")
        } ?: run {
            Log.w(tag, "openDevice: usbDeviceConnection fileDescriptor is null")
        }

        return usbDeviceConnection != null
    }

    fun closeDevice() {
        usbDeviceConnection?.close() // 关闭USB设备
        usbDeviceConnection = null
        usbDevice = null
    }

    fun getConfiguration(index: Int): Boolean {
        if (usbDeviceConnection == null) {
            Log.e(tag, "getConfiguration: usbDeviceConnection is null")
            return false
        }

        usbConfiguration = usbDevice?.getConfiguration(index) // 获取USB设备配置
        Log.d(tag, "getConfiguration: usbConfiguration = $usbConfiguration")
        return usbConfiguration != null
    }

    fun getInterface(index: Int): Boolean {
        if (usbConfiguration == null) {
            Log.e(tag, "getInterface: usbConfiguration is null")
            return false
        }

        Log.d(tag, "getInterface: index = $index")



        usbInterface = usbConfiguration?.getInterface(index) // 获取USB接口
        Log.d(tag, "getInterface: usbInterface = $usbInterface")
        return usbInterface != null
    }

    fun setInterface(): Boolean {
        if (usbDeviceConnection == null) {
            Log.e(tag, "setInterface: usbDeviceConnection is null")
            return false
        }


        return usbDeviceConnection?.setInterface(usbInterface) ?: false // 设置USB接口
    }

    fun claimInterface(): Boolean {
        if (usbDeviceConnection == null) {
            Log.e(tag, "claimInterface: usbDeviceConnection is null")
            return false
        }
        return usbDeviceConnection?.claimInterface(usbInterface, true) ?: false // 获取USB接口权限
    }

    fun releaseInterface(): Boolean {
        if (usbDeviceConnection == null) {
            Log.e(tag, "releaseInterface: usbDeviceConnection is null")
            return false
        }
        return usbDeviceConnection?.releaseInterface(usbInterface) ?: false // 释放USB接口权限
    }

    fun getEndpoint(inIndex:Int?,outIndex:Int?): Boolean {
        Log.d(tag, "getEndpoint: inIndex = $inIndex, outIndex = $outIndex")

        if (usbInterface == null) {
            Log.w(tag, "getEndpoint: usbInterface is null")
            return false
        }

        usbEndpointIn = null
        usbEndpointOut = null

        if(inIndex != null){
            usbEndpointIn = usbInterface!!.getEndpoint(inIndex)
            if(usbEndpointIn == null){
                Log.w(tag, "getEndpoint: usbEndpointIn is null, inIndex = $inIndex")
                return false
            }
            if(usbEndpointIn!!.direction != UsbConstants.USB_DIR_IN){
                Log.w(tag, "getEndpoint: usbEndpointIn direction is not USB_DIR_IN, inIndex = $inIndex")
                return false
            }

            Log.d(tag, "getEndpoint: usbEndpointIn = $usbEndpointIn, inIndex = $inIndex")
        }

        if(outIndex != null){
            usbEndpointOut = usbInterface!!.getEndpoint(outIndex)
            if(usbEndpointOut == null){
                Log.w(tag, "getEndpoint: usbEndpointOut is null, outIndex = $outIndex")
                return false
            }
            if(usbEndpointOut!!.direction != UsbConstants.USB_DIR_OUT){
                Log.w(tag, "getEndpoint: usbEndpointOut direction is not USB_DIR_OUT, outIndex = $outIndex")
                return false
            }

            Log.d(tag, "getEndpoint: usbEndpointOut = $usbEndpointOut, outIndex = $outIndex")
        }

        if (usbEndpointIn != null && usbEndpointOut != null) {
            return true
        }


        for (i in 0 until usbInterface!!.endpointCount) { // 遍历USB接口的端点
            val endpoint = usbInterface!!.getEndpoint(i)
            Log.d(tag, "getEndpoint: <${i}> endpoint = ${endpoint.address}, ${endpoint.type}, ${endpoint.direction}")
            // 获取USB端点
            if (endpoint.type == UsbConstants.USB_ENDPOINT_XFER_BULK) { // 判断是否为批量传输端点
                if (endpoint.direction == UsbConstants.USB_DIR_IN) { // 判断是否为输入端点
                    if(usbEndpointIn == null){
                        usbEndpointIn = endpoint // 获取输入端点
                        Log.d(tag, "getEndpoint: usbEndpointIn = $usbEndpointIn, type = ${endpoint.type}, direction = ${endpoint.direction}, maxPacketSize = ${endpoint.maxPacketSize}, interval = ${endpoint.interval}")
                    }

                } else if (endpoint.direction == UsbConstants.USB_DIR_OUT) { // 判断是否为输出端点
                    if(usbEndpointOut == null){
                        usbEndpointOut = endpoint // 获取输出端点
                        Log.d(tag, "getEndpoint: usbEndpointOut = $usbEndpointOut, type = ${endpoint.type}, direction = ${endpoint.direction}, maxPacketSize = ${endpoint.maxPacketSize}")
                    }
                }
            }
        }

        Log.d(tag, "getEndpoint: usbEndpointIn = $usbEndpointIn, usbEndpointOut = $usbEndpointOut")
        return usbEndpointOut != null
    }

    private fun bulkTransferOut(data: ByteArray): Int {
        if (usbDeviceConnection == null) {
            Log.e(tag, "bulkTransferOut: usbDeviceConnection is null")
            return -1
        }

        val maxPacketSize = 16384


        if(data.size > maxPacketSize){
            //分包发送
            var offset = 0
            while(offset < data.size){
                var length = maxPacketSize
                if(offset + length > data.size){
                    length = data.size - offset
                }
                val ret = usbDeviceConnection?.bulkTransfer(usbEndpointOut, data, offset, length, 2000)
                if (ret == null || ret < 0) {
                    Log.w(tag, "发送数据失败1 bulkTransferOut: ret = $ret, data = ${data.size}, offset = $offset, length = $length")
                    return -1
                }
                offset += length
            }
        }else{
            val ret = usbDeviceConnection?.bulkTransfer(usbEndpointOut, data, data.size, 2000)
            if (ret == null || ret < 0) {
                Log.w(tag, "发送数据失败2 bulkTransferOut: ret = $ret, data = ${data.size}")
                return -1
            }
        }

        return data.size // 向USB设备的输出端点发送数据
    }

    private fun bulkTransferIn(data: ByteArray): Int {


        if (usbDeviceConnection == null) {
            Log.e(tag, "bulkTransferIn: usbDeviceConnection is null")
            return -1
        }

        val ret = usbDeviceConnection?.bulkTransfer(usbEndpointIn, data, data.size, 2000)


        if (ret == null || ret < 0) {
            Log.w(tag, "接收数据 bulkTransferIn: ret = ${ret}, data = ${data.size} ")
            return -1
        }
        //Log.d(tag, "接收数据 bulkTransferIn: ret = $ret, data = ${data.size}")
        return ret // 从USB设备的输入端点接收数据

    }


    fun controlTransfer(
        requestType: Int,
        request: Int,
        value: Int,
        index: Int,
        data: ByteArray
    ): Boolean {
        if (usbDeviceConnection == null) {
            Log.e(tag, "controlTransferOut: usbDeviceConnection is null")
            return false
        }
        val res = usbDeviceConnection?.controlTransfer(
            requestType,
            request,
            value,
            index,
            data,
            data.size,
            1000
        )   // 向USB设备发送控制命令
        if (res == null || res < 0) {
            Log.w(tag, "controlTransferOut: res = $res")
            return false
        }

        return true
    }

    fun readData(maxLength: Int): ByteArray? {
        val byteArray = ByteArray(maxLength)

        val readLength = bulkTransferIn(byteArray)
        if (readLength <= 0) {
            Log.w(tag, "readData: bulkTransferIn failed")
            return null
        }
        //Log.d(tag, "readData length = $readLength, data: ${byteArray.copyOf(readLength).toHexString()}")
        return byteArray.copyOf(readLength)
    }

    fun writeData(data: ByteArray): Boolean {
        val writeLength = bulkTransferOut(data)
        if (writeLength <= 0) {
            Log.w(tag, "writeData: bulkTransferOut failed")
            return false
        }
        return true
    }


    @RequiresApi(Build.VERSION_CODES.O)
    fun startDataListeningPipelined(
        callback: (ByteArray) -> Unit,
        accumulatedBufferSize: Int = 76800,
        requestCount: Int = 64,
        bufferSize: Int = 8192
    ) {

        Log.d(tag, "startDataListeningPipelined: accumulatedBufferSize = $accumulatedBufferSize, requestCount = $requestCount, bufferSize = $bufferSize")

        if (usbDeviceConnection == null) {
            Log.e(tag, "startDataListeningPipelined: usbDeviceConnection is null")
            return
        }
        if (usbEndpointIn == null) {
            Log.e(tag, "startDataListeningPipelined: usbEndpointIn is null")
            return
        }
        if (dataListeningRunning) {
            Log.w(tag, "startDataListeningPipelined: dataListeningRunning = true")
            return
        }

        dataListeningRunning = true

        // === 使用高优先级线程调度器来启动协程 ===
        CoroutineScope(highPriorityDispatcher).launch {
            try {
                // 1. 创建多个 UsbRequest，每个都要单独的 Buffer
                val requestList = ArrayList<UsbRequest>(requestCount)
                val bufferList = ArrayList<ByteBuffer>(requestCount)
                //上一个buffer
                var lastByteArray: ByteArray? = null
                //累计buffer
                var dataIndex = 0


                for (i in 0 until requestCount) {
                    val buffer = ByteBuffer.allocateDirect(bufferSize)
                    val usbRequest = UsbRequest()
                    val initOk = usbRequest.initialize(usbDeviceConnection, usbEndpointIn)
                    if (!initOk) {
                        Log.e(tag, "startDataListeningPipelined: Failed to init request #$i")
                        break
                    }
                    // 将 (request, buffer) 都存起来
                    requestList.add(usbRequest)
                    bufferList.add(buffer)
                }

                // 2. 先把它们全部 queue 进管线
                for (i in requestList.indices) {
                    val queued = requestList[i].queue(bufferList[i])
                    if (!queued) {
                        Log.e(tag, "startDataListeningPipelined: Failed to queue request #$i")
                    } else {
                        Log.d(tag, "startDataListeningPipelined: queue request #$i")
                    }
                }

                // == 新增一个 ByteArrayOutputStream 用来累加数据 ==
                val accumulatedData = java.io.ByteArrayOutputStream()

                // 3. 循环调用 requestWait，处理已完成的请求，然后再 re-queue
                while (dataListeningRunning) {

                    val completedRequest = usbDeviceConnection?.requestWait()
                    if (completedRequest != null && dataListeningRunning) {
                        // 找到对应的 index
                        val idx = requestList.indexOf(completedRequest)
                        if (idx != -1) {
                            // 取到对应 buffer
                            val buffer = bufferList[idx]
                            // 注意需要 buffer.flip() 再读取
                            buffer.flip()

                            dataLengthSum += buffer.remaining() // 累加数据长度
                            val receivedData = ByteArray(buffer.remaining())
                            buffer.get(receivedData)
                            dataIndex += 1

                            //LockSupport.parkNanos(50)

//                            val data0 = receivedData.getOrNull(0)?.toUByte()?.toInt() ?: -1
//
//                            Log.d(tag, "Received data from request #$idx, size = ${receivedData.size}, dataIndex = $dataIndex, data0 = $data0")

//                            val head0 = receivedData[0].toUByte().toInt()
//                            if(head0 != 12){
//                                Log.d(tag, "<${dataIndex}> <$idx> head0 = $head0, receivedData = ${receivedData.size}")
//                            }

                            if(accumulatedBufferSize == 0){
                                callback(receivedData)
                            }else{
                                accumulatedData.write(receivedData)
                                //== 如果累加后的总字节数 >= 10240，就回调并清空 ==
                                if (accumulatedData.size() >= accumulatedBufferSize) {
                                    val bigData = accumulatedData.toByteArray()

                                    // 回调给外部
                                    callback(bigData)

                                    // 清空，准备下一轮累加
                                    accumulatedData.reset()
                                }
                            }



                            // 再次重置 buffer 并 re-queue
                            buffer.clear()
                            val reQueued = completedRequest.queue(buffer)
                            if (!reQueued) {
                                Log.e(
                                    tag,
                                    "startDataListeningPipelined: Failed to re-queue request #$idx"
                                )
                            }
                        } else {
                            Log.w(tag, "startDataListeningPipelined: Unknown completed request")
                        }
                    }
                }

                // 4. 停止循环后，清理资源
                for (req in requestList) {
                    req.close() // 释放 UsbRequest
                }
                Log.d(tag, "startDataListeningPipelined: all requests closed")

            } catch (e: Exception) {
                Log.e(tag, "startDataListeningPipelined: Exception -> $e")
            }
        }
    }




    /**
    * 高吞吐量 USB 读管线：
    * 1. 使用 UsbRequest + requestWait 异步流水线获取最大带宽。
    * 2. 线程优先级调到 URGENT_AUDIO，降低调度延迟。
    * 3. 通过对象池复用 ByteBuffer，避免频繁 new / GC。
    * 4. 采用无拷贝环形缓冲区，将零散包快速拼成大块后回调。
    */
    @RequiresApi(Build.VERSION_CODES.O)
    @Suppress("BlockingMethodInNonBlockingContext")
    fun startDataListeningPipelined2(
        callback: (ByteArray) -> Unit,
        accumulatedBufferSize: Int = 76_800,      // 建议为端点包大小的整数倍
        requestCount: Int = 64,                   // ≥4 才能铺满 USB 总线
        bufferSize: Int = 8_192                   // 满足一次 bulk maxPacketSize 的整数倍
    ) {
        Log.d(tag, "startDataListeningPipelined2: accumulatedBufferSize = $accumulatedBufferSize, requestCount = $requestCount, bufferSize = $bufferSize")

        // ----------- 前置校验 -----------
        if (usbDeviceConnection == null || usbEndpointIn == null) {
            Log.e(tag, "USB 未就绪，无法开始监听")
            return
        }
        if (dataListeningRunning) {
            Log.w(tag, "监听已在运行")
            return
        }

        dataListeningRunning = true // 标记监听已开始

        // ----------- 准备对象池 -----------
        val reqPool  = ArrayList<UsbRequest>(requestCount)
        val bufPool  = ArrayList<ByteBuffer>(requestCount)
        repeat(requestCount) {
            val buf = ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.LITTLE_ENDIAN)
            val req = UsbRequest().apply {
                if (!initialize(usbDeviceConnection, usbEndpointIn)) {
                    Log.e(tag, "UsbRequest init 失败 #$it"); return
                }
                queue(buf)
            }
            bufPool += buf
            reqPool += req
        }

        // ----------- 专用高优先级协程 -----------
        CoroutineScope(highPriorityDispatcher).launch {
            // 将线程优先级提高，效果 ≈ native thread + sched_fifo
           // Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO)

            // 零拷贝环形缓冲区（避免 ByteArrayOutputStream 的二次拷贝）
            //val ring = RingByteBuffer(accumulatedBufferSize*2)
            // == 新增一个 ByteArrayOutputStream 用来累加数据 ==
            val accumulatedData = java.io.ByteArrayOutputStream()

            try {
                while (dataListeningRunning) {
                    val doneReq = usbDeviceConnection?.requestWait() ?: continue
                    val idx = reqPool.indexOf(doneReq)
                    if (idx == -1) continue      // 理论上不会发生

                    val buf = bufPool[idx]
                    buf.flip()
                    dataLengthSum += buf.remaining() // 累加数据长度
                    val receivedData = ByteArray(buf.remaining())
                    buf.get(receivedData)

                    //Log.d(tag, "监听到数据 #$idx，大小 = ${buf.remaining()}")

                    // === 累加 ===
                    accumulatedData.write(receivedData)
                    buf.clear()

                    // 立即回调或满足阈值回调
//                    if (accumulatedBufferSize == 0 || ring.size() >= accumulatedBufferSize) {
//                        Log.d(tag, "回调数据，大小 = ${ring.size()}")
//                        callback(ring.readAll())
//                    }

                    if(accumulatedBufferSize == 0){
                        val bigData = accumulatedData.toByteArray()
                        // 回调给外部
                        callback(bigData)

                        // 清空，准备下一轮累加
                        accumulatedData.reset()
                    }else{

                        //== 如果累加后的总字节数 >= 10240，就回调并清空 ==
                        if (accumulatedData.size() >= accumulatedBufferSize) {
                            //Log.d(tag, "回调数据，大小 = ${accumulatedData.size()}")
                            val bigData = accumulatedData.toByteArray()
                            // 回调给外部
                            callback(bigData)

                            // 清空，准备下一轮累加
                            accumulatedData.reset()
                        }
                    }


                    // 重新入队，维持管线深度
                    if (!doneReq.queue(buf)) {
                        Log.e(tag, "re-queue 失败 #$idx，停止监听")
                        break
                    }
                }
            } catch (t: Throwable) {
                Log.e(tag, "监听异常", t)
            } finally {
                Log.d(tag, "监听结束，清理资源, dataListeningRunning = $dataListeningRunning")
                // -------- 资源清理 --------
                reqPool.forEach { it.close() }
                dataListeningRunning = false // 标记监听已停止
                Log.d(tag, "数据监听已停止")
            }
        }
    }

    /**
     * 高吞吐 USB 数据监听（第三版）
     *
     * - 零拷贝环形缓冲区
     * - 使用 UsbRequest.clientData 取代列表查找
     * - 读线程只写 Channel，不做耗时逻辑
     */
    @RequiresApi(Build.VERSION_CODES.O)
    @Suppress("EXPERIMENTAL_API_USAGE")
    fun startDataListeningPipelined3(
        callback: suspend (ByteArray) -> Unit,
        accumulatedThreshold: Int = 76_800,   // 满足上层解码一帧的大小
        requestCount: Int = 64,               // 建议 ≥ 4
        bufferSize: Int = 8_192               // 必须为端点 maxPacketSize 整数倍
    ) {
        if (usbDeviceConnection == null || usbEndpointIn == null) {
            Log.e(tag, "USB 未就绪，无法开始监听")
            return
        }
        if (dataListeningRunning) return
        dataListeningRunning = true

        val myHighPrioDispatcher: CoroutineDispatcher by lazy {
            Executors.newSingleThreadExecutor { r ->
                Thread(r, "UsbFastRead").apply {
                    android.os.Process.setThreadPriority(
                        android.os.Process.THREAD_PRIORITY_URGENT_AUDIO
                    )
                }
            }.asCoroutineDispatcher()
        }

        /* ---------- 零拷贝环形缓冲 ---------- */
        val ring = RingByteBuffer(accumulatedThreshold * 6) // 6 倍余量

        /* ---------- 收发协程 ---------- */
        val chan = Channel<ByteArray>(Channel.UNLIMITED)

        CoroutineScope(myHighPrioDispatcher).launch {
            /* ① 预建请求池 */
            val requests = ArrayList<UsbRequest>(requestCount)
            repeat(requestCount) { idx ->
                val buf = ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.LITTLE_ENDIAN)
                val req = UsbRequest().apply {
                   val res =  initialize(usbDeviceConnection, usbEndpointIn)
                    Log.d(tag, "UsbRequest 初始化 #$idx: $res")
                    if (!res) {
                        Log.e(tag, "UsbRequest 初始化失败 #$idx")
                        return@apply
                    }
                    /* 关键！直接把 Buffer 绑在 Request 上 */
                    clientData = buf
                    queue(buf)
                }
                requests += req
            }

            try {
                while (isActive && dataListeningRunning) {
                    val done = usbDeviceConnection?.requestWait() ?: continue
                    val buf = done.clientData as ByteBuffer

                    /* 写入环形缓冲（零拷贝）*/
                    buf.flip() // ★ 必须先 flip

                    if (buf.remaining() <= 0) continue // 无数据则跳过
                    dataLengthSum += buf.remaining() // 累加数据长度

                    //Log.d(tag, "监听到数据，大小 = ${buf.remaining()}")
                    ring.write(buf)                                  // 不再传 len
                    buf.clear()                                      // 复用给下一次 queue



                    /* 达到阈值就转 ByteArray 投递到 Channel */
                    if (ring.size() >= accumulatedThreshold) {
                        ring.readAll()?.let { chan.trySend(it) }
                    }

                    /* 回炉重排 */
                    done.queue(buf)
                }
            } catch (t: Throwable) {
                Log.e(tag, "USB 监听异常", t)
            } finally {
                requests.forEach { it.close() }
                dataListeningRunning = false
                chan.close()
                Log.i(tag, "USB 数据监听结束")
            }
        }

        /* ② 消费协程（默认 Default）*/
        CoroutineScope(Dispatchers.Default).launch {
            for (packet in chan) {
                //Log.d(tag, "Received packet of size ${packet.size}")
                callback(packet)   // 业务线程，可做解码/保存等重活
            }
        }
    }

    fun stopDataListening() {
        dataListeningRunning = false
        dataListeningThread?.join()

        dataQueue.clear() // 清空数据队列
    }



}